package com.platform.oss;

import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.platform.utils.RRException;
import com.platform.utils.ResourceUtil;
import com.platform.utils.RunResult;
import com.platform.utils.StringUtils;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * AWS云存储
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-03-25 15:41
 */
public class AwsCloudStorageService extends CloudStorageService {
    public static final String FILE_SEPARATOR   =   "/";

    public static final String CONTENT_TYPE_IMAGE =   "image/jpeg";
    public static final String CONTENT_TYPE_WORD =   "application/msword";
    public static final String CONTENT_TYPE_PDF =   "application/pdf";

    private AmazonS3Client client;

    public AwsCloudStorageService(CloudStorageConfig config) {
        this.config = config;
        //初始化
        init();
    }

    private void init() {
        //创建客户端
        client = new AmazonS3Client();
        Region cnNorth1 = Region.getRegion(Regions.CN_NORTH_1);
        client.setRegion(cnNorth1);
    }

    @Override
    public String upload(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return upload(file.getBytes(), getPath(config.getQiniuPrefix()) + "." + prefix);
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(CONTENT_TYPE_IMAGE);
            metadata.setContentLength(inputStream.available());
            String bucketName = ResourceUtil.getConfigByName("aws.buckets");
            client.putObject(bucketName, path, inputStream, metadata);
        } catch (Exception e) {
            throw new RRException("上传文件失败", e);
        }
        return ResourceUtil.getConfigByName("aws.view") + path;
    }


}
